<template>
  <el-upload
    class="upload-demo"
    action=""
    ref="upload"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :http-request="handleUpload"
    :limit="1"
    :auto-upload="false"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
    :multiple = "false"
    :file-list="fileList">
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">点击上传</el-button>
  </el-upload>
</template>

<script>
    import { uploadFile } from '@/api/binding'
    export default {
      name: 'upload',
      data() {
        return {
          fileList: [],
          isUpload: true
        }
      },
      methods: {
        beforeUpload(file) {
          if (file.type !== 'application/octet-stream') {
            this.isUpload = false
            this.$message.error('只能上传.bin文件')
          } else {
            this.isUpload = true
          }
        },
        handleUpload(file, fileList) {
          console.log(fileList)
          const self = this
          if (this.isUpload) {
            const reader = new FileReader()
            reader.readAsDataURL(file.file)
            reader.onloadend = function() {
              const data = {}
              data.fileBase64 = this.result
              uploadFile(data).then(response => {
                if (response.code === 1) {
                  self.$message({
                    message: '文件上传成功！',
                    type: 'success'
                  })
                } else {
                  self.$message.error('文件上传失败')
                }
              })
            }
          }
          this.fileList = []
        },
        submitUpload() {
          this.$refs.upload.submit()
        },
        handleRemove(file, fileList) {
          console.log(file, fileList)
        },
        handlePreview(file) {
          console.log(file)
        },
        handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
        },
        beforeRemove(file, fileList) {
          return this.$confirm('确定移除文件?')
        }
      }
    }
</script>

<style scoped>

</style>
